﻿using DevExpress.Utils;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mMachine.UI
{
    public partial class frmMAC_Equipment_Assets_Info : frmBaseDataForm
    {
        static DataTable dtComlist = new DataTable();
        static Common.GetDataTable comm = new Common.GetDataTable();
        public frmMAC_Equipment_Assets_Info()
        {
            InitializeComponent();
            InitializeForm();
            dtComlist = comm.GetValuesOption();
            ComboxList_ASSET_STATE();
            GetSearchLookUpEdit();
        }
        private void frmMAC_Equipment_Assets_Info_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
        }
        protected override void InitializeForm()
        {
            _SummaryView = new DevGridView(gridView1);
            gridView1.DoubleClick += new EventHandler(OnGridViewDoubleClick); //主表DoubleClict
            frmGridViewCust.RegisterGrid(gridView1);
            DevStyle.SetGridControlLayout(gridControl1, false);//表格设置   

            DevStyle.SetSummaryGridViewLayout(gridView1);
            DevStyle.SetDetailGridViewLayout(gridView1);
            ShowSummary(); //下载显示数据.
            tpSummary = xtraTabPage1;
            tcBusiness = xtraTabControl1;
            tpSummary.PageVisible = true;
            //tpDetail.PageVisible = false;
            tcBusiness.ShowTabHeader = DefaultBoolean.True;
            tcBusiness.SelectedTabPage = tpSummary;
        }
        private void ShowSummary()
        {
            try
            {
                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public override void DoView(Lamex.Interface.IButtonInfo sender)
        {
            string sqlWhere = "";
            string sql = @"SELECT [MACHINE_NO]
      ,[INVENTORY_NO]
      ,[ASSET_NO]
      ,[CE_NO]
      ,[PURCHASE_AMOUNT]
      ,CONVERT(VARCHAR(10),PURCHASE_DATE,120) [PURCHASE_DATE]
      ,[DURABLE_YEARS]
      ,[ASSET_STATE]
      ,[UPDATE_TIME]
      ,[UPDATE_USER]
  FROM [LamexMESManager].[dbo].[FAMA_Account_Assets_Info] WHERE 1=1";
            if (!string.IsNullOrEmpty(txtMACHINE_NO.Text))
            {
                sqlWhere += " and MACHINE_NO like '%" + txtMACHINE_NO.Text + "%'";
            }
            if (!string.IsNullOrEmpty(txtASSET_NO.Text))
            {
                sqlWhere += " and ASSET_NO like '%" + txtASSET_NO.Text + "%'";
            }
            if (!string.IsNullOrEmpty(txtINVENTORY_NO.Text))
            {
                sqlWhere += " and INVENTORY_NO like '%" + txtINVENTORY_NO.Text + "%'";
            }

            sql = sql + sqlWhere + " order by UPDATE_TIME desc ";
            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);
            DoBindingSummaryGrid(dt);
            gridView1.BestFitColumns();
            this.gridView1.OptionsView.ColumnAutoWidth = false;
            base.DoView(sender);

        }
        //新增
        public override void DoAdd(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            // if (!BuildSqlHelper.IsExistList("FAMA_Account_Basic_Info")) return;
            #endregion
            // xtraTabPage1.PageEnabled = false;
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;
            Initiallize();
           // GetSearchLookUpEdit();
            IsEdit = "Add";
            base.DoAdd(sender);
        }
        //绑定设备编号值
        public void GetSearchLookUpEdit()
        {
            string sql = @" SELECT MACHINE_NO,MACHINE_NAME,MACHINE_DESC FROM [LamexMESManager].[dbo].[FAMA_Account_Basic_Info]";
            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);
            EDIT_MACHINE_NO.Properties.ValueMember = "MACHINE_NO";
            EDIT_MACHINE_NO.Properties.DisplayMember = "MACHINE_NO";
            EDIT_MACHINE_NO.Properties.DataSource = dt;
            txtMACHINE_NO.Properties.ValueMember = "MACHINE_NO";
            txtMACHINE_NO.Properties.DisplayMember = "MACHINE_NO";
            txtMACHINE_NO.Properties.DataSource = dt;
        }
        //初始化新增信息
        public void Initiallize()
        {
            EDIT_MACHINE_NO.Text = "";//设备编号
            EDIT_INVENTORY_NO.Text = "";//存货号
            EDIT_ASSET_NO.Text = "";//资产编号
            EDIT_CE_NO.Text = "";//CE编号
            EDIT_PURCHASE_AMOUNT.Text = "";//采购金额(元)
            EDIT_PURCHASE_DATE.Text = "";//采购日期
            EDIT_DURABLE_YEARS.Text = "";//使用年限
            EDIT_ASSET_STATE.Text = "";//资产状态
            IsEdit = "";
        }
        //编辑
        public override void DoEdit(Lamex.Interface.IButtonInfo sender)
        {
            if (gridView1.SelectedRowsCount == 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("【没有选中要修改的数据！】", "提示", MessageBoxButtons.OK);
                return;
            }
            int m = gridView1.FocusedRowHandle;
            DataRow dr = gridView1.GetDataRow(m);
            KeysName = dr["MACHINE_NO"].ToString();
            xtraTabPage1.PageEnabled = false;
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;
            IsEdit = "Edit";
           // GetSearchLookUpEdit();

            //加载数据
            EDIT_MACHINE_NO.Text = KeysName;//设备编号
            EDIT_INVENTORY_NO.Text = dr["INVENTORY_NO"].ToString();//存货号
            EDIT_ASSET_NO.Text = dr["ASSET_NO"].ToString();//资产编号
            EDIT_CE_NO.Text = dr["CE_NO"].ToString();//CE编号
            EDIT_PURCHASE_AMOUNT.Text = dr["PURCHASE_AMOUNT"].ToString();//采购金额(元)
            EDIT_PURCHASE_DATE.Text = dr["PURCHASE_DATE"].ToString();//采购日期
            EDIT_DURABLE_YEARS.Text = dr["DURABLE_YEARS"].ToString();//使用年限
            EDIT_ASSET_STATE.Text = dr["ASSET_STATE"].ToString();//资产状态    
            base.DoEdit(sender);
        }
        //保存
        public override void DoSave(Lamex.Interface.IButtonInfo sender)
        {
            try
            {
                if (string.IsNullOrEmpty(EDIT_MACHINE_NO.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("设备编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrEmpty(EDIT_INVENTORY_NO.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("存货号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrEmpty(EDIT_ASSET_NO.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("资产编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrEmpty(EDIT_CE_NO.Text))
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("CE编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrEmpty(EDIT_PURCHASE_AMOUNT.Text) || Convert.ToDecimal(EDIT_PURCHASE_AMOUNT.Text) <= 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("购买金额不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                string STRMACHINE_NO = EDIT_MACHINE_NO.Text;//设备编号
                string STRINVENTORY_NO = EDIT_INVENTORY_NO.Text;//存货号
                string STRASSET_NO = EDIT_ASSET_NO.Text; //资产编号
                string STRCE_NO = EDIT_CE_NO.Text;//CE编号
                Decimal STRPURCHASE_AMOUNT = Convert.ToDecimal(EDIT_PURCHASE_AMOUNT.Text.Length > 0 ? EDIT_PURCHASE_AMOUNT.Text : null);//采购金额(元)
                string STRPURCHASE_DATE = EDIT_PURCHASE_DATE.Text.Length>0? "'"+ EDIT_PURCHASE_DATE.Text + "'":"NULL";//采购日期
                int STRDURABLE_YEARS = Convert.ToInt32(EDIT_DURABLE_YEARS.Text.Length > 0 ? EDIT_DURABLE_YEARS.Text : null);//使用年限
                string STRASSET_STATE = EDIT_ASSET_STATE.Text;//资产状态
                //DateTime UPDATE_TIME = DateTime.Now;//创建时间
                string UPDATE_USER = Lamex.Common.Loginer.CurrentUser.Account;//修改人
                if (IsEdit == "Add")
                {
                    string sql_Insert = @"INSERT INTO [LamexMESManager].[dbo].[FAMA_Account_Assets_Info]( [MACHINE_NO]
      ,[INVENTORY_NO]
      ,[ASSET_NO]
      ,[CE_NO]
      ,[PURCHASE_AMOUNT]
      ,[PURCHASE_DATE]
      ,[DURABLE_YEARS]
      ,[ASSET_STATE]
      ,[UPDATE_TIME]
      ,[UPDATE_USER])
	  VALUES('" + STRMACHINE_NO + "','" + STRINVENTORY_NO + "','" + STRASSET_NO + "','" + STRCE_NO +
      "'," + STRPURCHASE_AMOUNT + "," + STRPURCHASE_DATE + "," + STRDURABLE_YEARS + ",'" + STRASSET_STATE +
      "',GETDATE(),'" + UPDATE_USER + "')";

                    if (BaseBuildSql.ExecuteNonQuery(sql_Insert) > 0)

                        DevExpress.XtraEditors.XtraMessageBox.Show("新增成功", "提示", MessageBoxButtons.OK);
                    else
                        DevExpress.XtraEditors.XtraMessageBox.Show("新增失败", "提示", MessageBoxButtons.OK);
                }
                if (IsEdit == "Edit")
                {
                    string sql_Update = @"UPDATE [LamexMESManager].[dbo].[FAMA_Account_Assets_Info] SET 
      [INVENTORY_NO]='" + STRINVENTORY_NO + @"'
      ,[ASSET_NO]='" + STRASSET_NO + @"'
      ,[CE_NO]='" + STRCE_NO + @"'
      ,[PURCHASE_AMOUNT]=" + STRPURCHASE_AMOUNT + @"
      ,[PURCHASE_DATE]=" + STRPURCHASE_DATE + @"
      ,[DURABLE_YEARS]=" + STRDURABLE_YEARS + @"
      ,[ASSET_STATE]='" + STRASSET_STATE + @"'
      ,[UPDATE_TIME]=GETDATE()
      ,[UPDATE_USER]='" + UPDATE_USER + "' WHERE MACHINE_NO='"+ STRMACHINE_NO + "'";
                    if (BaseBuildSql.ExecuteNonQuery(sql_Update) > 0)
                        DevExpress.XtraEditors.XtraMessageBox.Show("修改成功", "提示", MessageBoxButtons.OK);
                    else
                        DevExpress.XtraEditors.XtraMessageBox.Show("修改失败", "提示", MessageBoxButtons.OK);
                }

                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;
                DoView(null);
                Initiallize();
                base.DoSave(sender);

            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public override void DoExport(IButtonInfo sender)
        {
            if (!Directory.Exists(@"D:\MESTemp"))
                Directory.CreateDirectory(@"D:\MESTemp");
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "导出Excel";
            fileDialog.InitialDirectory = @"D:\MESTemp";//导出默认路径
            fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";//导出默认格式
            fileDialog.FileName = "MES_TEMP_" + DateTime.Now.ToString("yyMMdd_hhMMss");//导出默认名称
            DialogResult dialogResult = fileDialog.ShowDialog(this);
            if (dialogResult == DialogResult.OK)
            {
                //导出表【IE_Part_TaskList】中当前产品类型，无“工艺路线标识”的数据

                string sqlWhere = "";
                string sql = @"SELECT [MACHINE_NO]
      ,[INVENTORY_NO]
      ,[ASSET_NO]
      ,[CE_NO]
      ,[PURCHASE_AMOUNT]
      ,CONVERT(VARCHAR(10),PURCHASE_DATE,120) [PURCHASE_DATE]
      ,[DURABLE_YEARS]
      ,[ASSET_STATE]
      ,[UPDATE_TIME]
      ,[UPDATE_USER]
  FROM [LamexMESManager].[dbo].[FAMA_Account_Assets_Info] WHERE 1=1";
                if (!string.IsNullOrEmpty(txtMACHINE_NO.Text))
                {
                    sqlWhere += " and MACHINE_NO like '%" + txtMACHINE_NO.Text + "%'";
                }
                if (!string.IsNullOrEmpty(txtASSET_NO.Text))
                {
                    sqlWhere += " and ASSET_NO like '%" + txtASSET_NO.Text + "%'";
                }
                if (!string.IsNullOrEmpty(txtINVENTORY_NO.Text))
                {
                    sqlWhere += " and INVENTORY_NO like '%" + txtINVENTORY_NO.Text + "%'";
                }

                sql = sql + sqlWhere + " order by UPDATE_TIME desc ";
                DataTable dtList = BaseBuildSql.GetDataTableBySql(sql);

                GridControl grid = new GridControl();
                GridView view = new GridView();
                grid.ViewCollection.Add(view);
                grid.MainView = view;
                view.GridControl = grid;
                foreach (DataColumn dc in dtList.Columns)
                {
                    DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
                    gridColumnNumber.FieldName = dc.ColumnName;
                }
                grid.DataSource = dtList;
                this.Controls.Add(grid);
                grid.ForceInitialize();//强制初始化
                //Font font = new Font("宋体", 11, FontStyle.Bold); 
                //view.Appearance.HeaderPanel.Font = font;
                //view.Appearance.Row.Font = font;            
                view.BestFitColumns();
                view.OptionsView.ColumnAutoWidth = false;
                view.OptionsView.ShowAutoFilterRow = false;
                view.OptionsPrint.PrintHorzLines = false;//去掉水平网格线
                view.OptionsPrint.PrintVertLines = false;//去掉垂直网格线
                view.ExportToXlsx(fileDialog.FileName);
                if (DevExpress.XtraEditors.XtraMessageBox.Show("导出成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    System.Diagnostics.Process.Start(fileDialog.FileName);//打开指定路径下的文件

            }
        }
        public void ComboxList_ASSET_STATE()
        {
            DataTable dt = new DataTable();
            dt = dtComlist.Select("VALUE_NAME='资产状态'").CopyToDataTable();
            EDIT_ASSET_STATE.Text = "";
            EDIT_ASSET_STATE.Properties.Items.Clear();
            string[] values = dt.Rows[0]["VALUE_OPTION"].ToString().Split(';');
            foreach (var item in values)
            {
                EDIT_ASSET_STATE.Properties.Items.Add(item);
            }
        }
        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            DoEdit(null);
        }
    }
}
